<template>
  <div class="course-base-info-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑课程信息' : '新增课程信息' }}</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleCopyCourse" v-if="!isEdit">
              复制创建新课程
            </el-button>
            <el-button @click="handleBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="140px"
        class="course-form"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程序号" prop="courseId" required>
              <el-input 
                v-model="formData.courseId" 
                placeholder="请输入课程序号（如：ZX34008511）"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="name" required>
              <el-input 
                v-model="formData.name" 
                placeholder="请输入课程名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程英文名">
              <el-input 
                v-model="formData.en_name" 
                placeholder="请输入课程英文名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程平台">
              <el-select v-model="formData.platform" placeholder="请选择课程平台" style="width: 100%;">
                <el-option label="通识教育平台" value="通识教育平台" />
                <el-option label="专业教育平台" value="专业教育平台" />
                <el-option label="实践教育平台" value="实践教育平台" />
                <el-option label="拓展协同平台" value="拓展协同平台" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程类别">
              <el-select v-model="formData.type" placeholder="请选择课程类别" style="width: 100%;">
                <el-option label="公共必修" value="公共必修" />
                <el-option label="公共选修" value="公共选修" />
                <el-option label="专业必修" value="专业必修" />
                <el-option label="专业选修" value="专业选修" />
              </el-select>
            </el-form-item>
          </el-col>
                     <el-col :span="12">
             <el-form-item label="课程模块">
               <el-input
                 v-model="formData.module"
                 placeholder="请输入课程模块（如：思想政治、大学外语、计算机基础等）"
                 style="width: 100%;"
                 clearable
               />
             </el-form-item>
           </el-col>
        </el-row>

                 <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="授课教师">
               <el-input
                 v-model="formData.teacher"
                 placeholder="请输入授课教师姓名"
                 style="width: 100%;"
                 clearable
               />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="辅导教师">
               <el-input
                 v-model="formData.tutor_teacher"
                 placeholder="请输入辅导教师姓名"
                 style="width: 100%;"
                 clearable
               />
             </el-form-item>
           </el-col>
         </el-row>

         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="授课年级" prop="grade" required>
               <el-input
                 v-model="formData.grade"
                 placeholder="请输入年级（如：2024）"
                 style="width: 100%;"
                 clearable
               />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="专业" prop="major" required>
               <el-select
                 v-model="formData.major"
                 placeholder="请选择专业"
                 style="width: 100%;"
                 :loading="majorsLoading"
                 filterable
                 clearable
               >
                 <el-option
                   v-for="major in majorsForSelect"
                   :key="major.id"
                   :label="major.name"
                   :value="major.name"
                 />
               </el-select>
             </el-form-item>
           </el-col>
         </el-row>

        <!-- 学分设置 -->
        <el-divider content-position="left">学分设置</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="总学分" prop="total_credit" required>
              <el-input-number 
                v-model="formData.total_credit" 
                :min="0" 
                :max="20" 
                :precision="1"
                style="width: 100%;"
                @change="calculateTotalCredit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="理论学分">
              <el-input-number 
                v-model="formData.theory_credit" 
                :min="0" 
                :max="20" 
                :precision="1"
                style="width: 100%;"
                @change="calculateTotalCredit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实践学分">
              <el-input-number 
                v-model="formData.practice_credit" 
                :min="0" 
                :max="20" 
                :precision="1"
                style="width: 100%;"
                @change="calculateTotalCredit"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 课时设置 -->
        <el-divider content-position="left">课时设置</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="教学周数">
              <el-input-number 
                v-model="formData.teach_week" 
                :min="1" 
                :max="20" 
                :precision="0"
                style="width: 100%;"
                @change="calculateTotalPeriod"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="周学时">
              <el-input-number 
                v-model="formData.period_per_week" 
                :min="1" 
                :max="20" 
                :precision="0"
                style="width: 100%;"
                @change="calculateTotalPeriod"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总学时" prop="total_period" required>
              <el-input-number 
                v-model="formData.total_period" 
                :min="0" 
                :max="200" 
                :precision="0"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="理论学时">
              <el-input-number 
                v-model="formData.theory_period" 
                :min="0" 
                :max="200" 
                :precision="0"
                style="width: 100%;"
                @change="calculateTotalPeriod"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实践学时">
              <el-input-number 
                v-model="formData.practice_period" 
                :min="0" 
                :max="200" 
                :precision="0"
                style="width: 100%;"
                @change="calculateTotalPeriod"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 课程关系 -->
        <el-divider content-position="left">课程关系</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="先修课程">
              <el-input
                v-model="formData.adv_course"
                placeholder="请输入先修课程"
                style="width: 100%;"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="后续课程">
              <el-input
                v-model="formData.follow_course"
                placeholder="请输入后续课程"
                style="width: 100%;"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 教材资源 -->
        <el-divider content-position="left">教材资源</el-divider>
        
        <el-form-item label="教材">
          <el-input
            v-model="formData.textbook"
            placeholder="请输入教材信息"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <el-form-item label="参考书">
          <el-input
            v-model="formData.reference_book"
            placeholder="请输入参考书信息"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <el-form-item label="教学资源">
          <el-input
            v-model="formData.resources"
            placeholder="请输入教学资源信息"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <!-- 其他信息 -->
        <el-divider content-position="left">其他信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="制定人">
              <el-input
                v-model="formData.prepared_by"
                placeholder="请输入制定人"
                style="width: 100%;"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核人">
              <el-input
                v-model="formData.reviewed_by"
                placeholder="请输入审核人"
                style="width: 100%;"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="制定依据">
          <el-input
            v-model="formData.according_to"
            placeholder="请输入制定依据"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <el-form-item label="执行目标">
          <el-input
            v-model="formData.execute_target"
            placeholder="请输入执行目标"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSave" :loading="saving">
            保存
          </el-button>
          <el-button type="success" @click="handleNext">
            下一项
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 复制课程对话框 -->
    <el-dialog
      v-model="copyDialogVisible"
      title="复制创建新课程"
      width="500px"
    >
      <el-form :model="copyForm" label-width="100px">
        <el-form-item label="课程序号" required>
          <el-input v-model="copyForm.courseId" placeholder="请输入新课程号" />
        </el-form-item>
                 <el-form-item label="年级" required>
           <el-input v-model="copyForm.grade" placeholder="请输入年级（如：2024）" />
         </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="copyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCopy">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { courseApi } from '@/api/courseApi.js'
import { majorApi } from '@/api/majorApi.js'

// 定义props
const props = defineProps({
  courseInfo: {
    type: Object,
    default: null
  }
})

// 定义emits
const emit = defineEmits(['next-step'])

// 响应式数据
const formRef = ref(null)
const majorsForSelect = ref([])
const majorsLoading = ref(false)
const saving = ref(false)
const copyDialogVisible = ref(false)
const isEdit = ref(false)
const courseId = ref(null)

// 表单数据
const formData = reactive({
  courseId: '',
  name: '',
  en_name: '',
  platform: '',
  type: '',
  module: '',
  teacher: '',
  tutor_teacher: '',
  grade: '',
  major: '',
  total_credit: 0,
  theory_credit: 0,
  practice_credit: 0,
  teach_week: 0,
  period_per_week: 0,
  total_period: 0,
  theory_period: 0,
  practice_period: 0,
  adv_course: '',
  follow_course: '',
  textbook: '',
  reference_book: '',
  resources: '',
  prepared_by: '',
  reviewed_by: '',
  according_to: '',
  execute_target: ''
})

// 复制表单数据
const copyForm = reactive({
  courseId: '',
  grade: ''
})

// 表单验证规则
const formRules = {
  courseId: [
    { required: true, message: '请输入课程序号', trigger: 'blur' },
    { pattern: /^[A-Z]{2}\d{8}$/, message: '课程序号格式为：2个大写字母+8位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请输入授课年级', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请选择专业', trigger: 'change' }
  ],
  total_credit: [
    { required: true, message: '请输入总学分', trigger: 'blur' }
  ],
  total_period: [
    { required: true, message: '请输入总学时', trigger: 'blur' }
  ]
}

// 加载课程信息（编辑模式）
const loadCourseInfo = async (id) => {
  try {
    const result = await courseApi.getCourseBaseInfo(id)
    const courseData = result.data || result
    
    // 清理数据，确保没有 null 值
    const cleanedData = {
      ...courseData,
      grade: courseData.grade || '',
      teach_week: courseData.teach_week || 0,
      period_per_week: courseData.period_per_week || 0,
      total_credit: courseData.total_credit || 0,
      theory_credit: courseData.theory_credit || 0,
      practice_credit: courseData.practice_credit || 0,
      total_period: courseData.total_period || 0,
      theory_period: courseData.theory_period || 0,
      practice_period: courseData.practice_period || 0
    }
    
    // 将查询到的数据填充到表单中
    Object.assign(formData, cleanedData)
    
    // 设置编辑模式
    isEdit.value = true
    courseId.value = id
    
    // 重新计算总学分和总课时
    calculateTotalCredit()
    calculateTotalPeriod()
  } catch (error) {
    console.error('加载课程信息失败:', error)
    ElMessage.error('加载课程信息失败')
  }
}

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    courseId: '',
    name: '',
    en_name: '',
    platform: '',
    type: '',
    module: '',
    teacher: '',
    tutor_teacher: '',
    grade: '',
    major: '',
    total_credit: 0,
    theory_credit: 0,
    practice_credit: 0,
    teach_week: 0,
    period_per_week: 0,
    total_period: 0,
    theory_period: 0,
    practice_period: 0,
    adv_course: '',
    follow_course: '',
    textbook: '',
    reference_book: '',
    resources: '',
    prepared_by: '',
    reviewed_by: '',
    according_to: '',
    execute_target: ''
  })
  isEdit.value = false
  courseId.value = null
}

// 监听props变化，如果有课程信息则填充表单
watch(() => props.courseInfo, async (newCourseInfo) => {
  if (newCourseInfo && Object.keys(newCourseInfo).length > 0) {
    if (newCourseInfo.id && Object.keys(newCourseInfo).length === 1) {
      // 如果只有ID，需要加载完整的课程信息
      await loadCourseInfo(newCourseInfo.id)
    } else {
      // 如果有完整的课程信息，直接填充表单
      // 清理数据，确保没有 null 值
      const cleanedCourseInfo = {
        ...newCourseInfo,
        grade: newCourseInfo.grade || '',
        teach_week: newCourseInfo.teach_week || 0,
        period_per_week: newCourseInfo.period_per_week || 0,
        total_credit: newCourseInfo.total_credit || 0,
        theory_credit: newCourseInfo.theory_credit || 0,
        practice_credit: newCourseInfo.practice_credit || 0,
        total_period: newCourseInfo.total_period || 0,
        theory_period: newCourseInfo.theory_period || 0,
        practice_period: newCourseInfo.practice_period || 0
      }
      Object.assign(formData, cleanedCourseInfo)
      isEdit.value = true
      courseId.value = newCourseInfo.id
    }
  } else {
    // 如果没有课程信息，清空表单并重置为新增模式
    handleReset()
  }
}, { immediate: true })

// 计算总学分
const calculateTotalCredit = () => {
  formData.total_credit = (formData.theory_credit || 0) + (formData.practice_credit || 0)
}

// 计算总学时
const calculateTotalPeriod = () => {
  if (formData.teach_week && formData.period_per_week) {
    formData.total_period = formData.teach_week * formData.period_per_week
  }
}

// 加载专业列表
const loadMajors = async () => {
  majorsLoading.value = true
  try {
    const result = await majorApi.getMajorList({ size: 1000 }) // 获取所有专业，不分页
    majorsForSelect.value = result.list || []
  } catch (error) {
    console.error('加载专业列表失败:', error)
    ElMessage.error('加载专业列表失败')
  } finally {
    majorsLoading.value = false
  }
}

// 保存课程信息
const handleSave = async () => {
  try {
    if (formRef.value) {
      await formRef.value.validate()
    }
    
    saving.value = true
    
    const courseData = { ...formData }
    
    let result
    if (isEdit.value) {
      // 编辑模式
      courseData.id = courseId.value
      result = await courseApi.updateCourseBaseInfo(courseData)
    } else {
      // 新增模式
      result = await courseApi.addCourseBaseInfo(courseData)
      // 保存成功后获取返回的ID
      if (result.data && result.data.id) {
        courseId.value = result.data.id
        isEdit.value = true
      }
    }
    
    
    if (result.success !== false) {
      ElMessage.success('保存成功')
      // 保存成功后清除表单数据并返回
      if (!isEdit.value) {
        handleReset()
      }
    } else {
      ElMessage.error('保存失败')
    }
  } catch (error) {
    console.error('保存课程信息失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 跳转到下一项（不保存）
const handleNext = () => {
  // 检查是否有基本的课程信息
  if (!formData.courseId || !formData.name) {
    ElMessage.warning('请先填写课程序号和课程名称')
    return
  }
  
  // 构建要传递的课程信息，包含自动查询所需的参数
  const courseInfo = {
    id: courseId.value || formData.courseId,
    ...formData,
    grade: formData.grade,
    major: formData.major,
    courseId: formData.courseId,
    courseName: formData.name
  }

  
  // 触发下一项事件
  emit('next-step', 'course-3', courseInfo)
}

// 返回
const handleBack = () => {
  // 清除URL参数
  const currentUrl = new URL(window.location.href)
  currentUrl.searchParams.delete('courseId')
  currentUrl.searchParams.delete('id')
  window.history.pushState({}, '', currentUrl.toString())
  
  // 触发自定义事件，通知父组件返回课程列表
  window.dispatchEvent(new CustomEvent('menuChange', {
    detail: { menuIndex: 'course-1' }
  }))
}

// 复制课程
const handleCopyCourse = () => {
  copyDialogVisible.value = true
}

// 确认复制
const confirmCopy = async () => {
  if (!copyForm.courseId || !copyForm.grade) {
    ElMessage.error('请填写课程序号和年级')
    return
  }
  
  try {
    // 根据课程序号和年级查询课程信息
    const result = await courseApi.getCourseByCourseIdAndGrade(copyForm.courseId, copyForm.grade)
    const courseData = result.data || result
    
    if (!courseData) {
      ElMessage.error('未找到对应的课程信息')
      return
    }
    
    // 复制数据，但清空课程序号、课程名称、授课年级和专业字段
    Object.assign(formData, courseData)
    formData.courseId = '' // 清空课程序号
    formData.name = '' // 清空课程名称
    formData.grade = '' // 清空授课年级
    formData.major = '' // 清空专业
    
    // 重新计算总学分和总课时
    calculateTotalCredit()
    calculateTotalPeriod()
    
    copyDialogVisible.value = false
    ElMessage.success('课程信息已复制，请完善课程信息')
  } catch (error) {
    console.error('查询课程信息失败:', error)
    ElMessage.error('查询课程信息失败，请检查课程序号和年级是否正确')
  }
}

// 组件挂载时检查是否为编辑模式
onMounted(() => {
  // 检查URL参数或路由参数，判断是否为编辑模式
  const urlParams = new URLSearchParams(window.location.search)
  const editId = urlParams.get('id')
  
  // 检查是否有课程ID参数（从课程列表跳转过来）
  const courseIdParam = urlParams.get('courseId')
  
  if (editId || courseIdParam) {
    isEdit.value = true
    courseId.value = editId || courseIdParam
    loadCourseInfo(editId || courseIdParam)
  }
  
  // 加载专业列表
  loadMajors()
})
</script>

<style scoped>
.course-base-info-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.course-form {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-divider__text) {
  font-weight: bold;
  color: #409EFF;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}
</style> 